package com.liu.service.impl;

import com.liu.controller.dto.PasswordDTO;
import com.liu.controller.dto.UserDTO;
import com.liu.mapper.UserMapper;
import com.liu.entity.User;
import com.liu.service.UserService;
import com.liu.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsy
 * @since 2023-01-15
 */
@Service("UserServiceImpl")
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public List<User> selectPage(Integer pageNum, Integer pageSize, String username, String address) {
        return userMapper.selectPage(pageNum,pageSize,username,address);
    }

    @Override
    public int selectTotal(String username,String address) {
        return userMapper.selectTotal(username,address);
    }

    @Override
    public User selectUserById(int id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public Boolean saveBatch(List<User> users) {
        return userMapper.saveBatch(users);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int updatePwd(PasswordDTO passwordDTO) {
        return userMapper.updatePwd(passwordDTO);
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        return userMapper.deleteByIds(ids);
    }

    @Override
    public User login(Map<String, Object> map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        User user = userMapper.findUserByName(username);
        log.info("user: {}",user);
        if(user == null) throw new RuntimeException("用户名输入错误，请重新输入");
        if (!user.getPassword().equals(password)) throw new RuntimeException("密码输入错误！");
        String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
        user.setToken(token);
        return user;
    }

    private User getUserInfo(UserDTO userDTO) {
        User one;
        try {
            one = findUserByName(userDTO.getUsername()); // 从数据库查询用户信息
        } catch (Exception e) {
            throw new RuntimeException("系统错误");
        }
        return one;
    }

    @Override
    public User findUserByName(String username) {
        return userMapper.findUserByName(username);
    }
}
